package com.gui.interceptor;

import com.gui.mapper.UserMapper;
import com.gui.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * SessionInterceptor
 *
 * @author guigu
 * @QQ 1170258867
 * @date 2020/6/11
 * @description
 */
@Component
public class SessionInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())){
                    User user =  userMapper.findbytoken(cookie.getValue());
                    request.getSession().setAttribute("user",user);
                    break;
                }
            }
        }
        return true;
    }
}
